package org.rambadger.command;

import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
import com.yammer.dropwizard.tasks.Task;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.mindrot.jbcrypt.BCrypt;
import org.rambadger.command.axon.AxonBundle;
import org.rambadger.command.command.CreateAdminUser;

import javax.ws.rs.WebApplicationException;
import java.io.PrintWriter;
import java.util.Collection;

import static org.rambadger.command.command.ChangeSystemRole.GrantAdmin;
import static org.rambadger.command.command.ChangeSystemRole.RevokeAdmin;

public class AlterAdminTask extends Task {
    CommandGateway gateway;

    public AlterAdminTask(AxonBundle axon) {
        super("manage_admins");
        this.gateway = axon.getCommandGateway();
    }

    @Override
    public void execute(ImmutableMultimap<String, String> parameters, PrintWriter output) throws Exception {
        String action = getFirst(parameters, "action");
        String username = getFirst(parameters, "username");
        switch (action) {
            case "create":
                String pwHash = BCrypt.hashpw(getFirst(parameters, "password"), BCrypt.gensalt());
                gateway.send(new CreateAdminUser(username, pwHash, getFirst(parameters, "email"), "", ""));
            case "grant":
                gateway.send(new GrantAdmin(username));
                break;
            case "revoke":
                gateway.send(new RevokeAdmin(username));
                break;
        }
    }

    private static <K,V> V getFirst(Multimap<K, V> map, K key) {
        Collection<V> items = map.get(key);
        if (items.isEmpty()) throw new WebApplicationException(200);
        else return items.iterator().next();

    }
}
